package com.ls.config;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author helen
 * @since 2019/10/16
 */
public class JwtUtils { //Jwt工具类

    public static final long EXPIRE = 1000 * 60 * 60 * 24; //设置token过期时间
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO"; //密钥

    public static void main(String[] args) {
        String token = getJwtToken("121", "王五");
        System.out.println(token);

        boolean b = checkToken(token);
        System.out.println(b);

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODgiLCJzdWIiOiJSb3NlIiwiaWF0IjoxNjM4NTE3MjU4LCJleHAiOjE2Mzg1MTcyODgsImlkIjoiMTIxIiwibmlja25hbWUiOiLnjovkupQifQ.h4gGbkGPCrukNBgWZE4ASCWCyInAc-Fws2let-MUjHc");
        System.out.println(claimsJws);
        String id = (String) claimsJws.getBody().get("id");
        String nickname = (String) claimsJws.getBody().get("nickname");
        System.out.println(id+"*****"+nickname);
    }

    //生成token字符串
    public static String getJwtToken(String id, String nickname) {

        JwtBuilder jwtBuilder = Jwts.builder()
                .setHeaderParam("typ", "JWT") //设置头信息
                .setHeaderParam("alg", "HS256")
                //声明的标识{"jti":"888"}
                .setId("888")
                //主体,用户{"sub":"Rose"}
                .setSubject("Rose")
                //创建日期
                .setIssuedAt(new Date()) //iat
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE)) //exp
                .claim("id", id) //设置token主体部分 存储用户信息
                .claim("nickname", nickname)
                //签名手段,参数1:算法,参数2:盐
                .signWith(SignatureAlgorithm.HS256, APP_SECRET);
        //获取jwt生成的token
        String jwtToken = jwtBuilder.compact();
        return jwtToken;
    }

    /**
     * 判断token是否存在与有效
     *
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if (StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     *
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if (StringUtils.isEmpty(jwtToken)) return false;
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token获取会员id
     *
     * @param request
     * @return
     */
    public static String getMemberIdByJwtToken(HttpServletRequest request) {
        System.out.println("------------");
        String jwtToken = request.getHeader("token");
        System.out.println("token: " + jwtToken);
        if (StringUtils.isEmpty(jwtToken)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("id");
    }
}
